/**
 * Author(s): xuming.Wong <xuming.Wong@gmail.com>
 */

#include "HttpDayTransactionQuery.h"

#include <QtNetwork/QNetworkReply>

#include "Utilities.h"
#include "StockDatabase.h"
#include "TransactionDatabase.h"
#include "QueryManager.h"

namespace QSThink
{

	HttpDayTransactionQuery::HttpDayTransactionQuery(int day,int symbol) 
		:_day(day),_symbol(symbol),_received(false),_netAccessMgr(this),_dataReaded(false)
	{
		
		QString url=buildQueryUrl(day,symbol);
		

		QNetworkRequest request;
		request.setUrl(QUrl(url));

		QNetworkReply* reply=_netAccessMgr.get(request);

		connect(&_netAccessMgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
		connect(reply, SIGNAL(readyRead()), this, SLOT(onReadyRead()));

		
	}

	bool HttpDayTransactionQuery::replyFinished( QNetworkReply* reply )
	{
		
		assert(false);
		QByteArray data = reply->readAll();

		//save data to database

		//_dayTrans=TransactionDatabase::getSingleton().addDayTransaction(_day,_symbol,data);

		QueryManager::getSingleton().OnTransactionsReturn(this);

		_dataReaded=true;
		return true;
	}


	bool HttpDayTransactionQuery::onReadyRead()
	{
		return true;

	}

	QString HttpDayTransactionQuery::buildQueryUrl( int day, int symbol )
	{
		
		QDate date=Utilities::getDateByDay(day);

		int yearDate=date.year();
		int monthDate=date.month();
		int dayDate=date.day();

		QString url="http://market.finance.sina.com.cn/downxls.php?date=";
		url+=QString::number(yearDate);

		if(monthDate<10){
			url+="-0";
		}else{
			url+="-";
		}

		url+=QString::number(monthDate);
		
		if(dayDate<10){
			url+="-0";
		}else{
			url+="-";
		}

		url+=QString::number(dayDate);
		url+="&symbol=";

		ExchangeType type=Utilities::getExchangeBySymbol(symbol);
		switch(type){
			case Exchange_ShangHai:
				url+="sh";
				url+=QString::number(symbol);
				break;
			case Exchange_ShenZhen:
				url+="sz";
				url+=QString::number(symbol);
				break;

		}

		return url;
	}

	Transaction1Day* HttpDayTransactionQuery::getDayTransaction()
	{
		return _dayTrans;
	}

}
